package kr.co.sdsway2.web.client;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import kr.co.sdsway2.comm.SdsWay2Util;
import kr.co.sdsway2.common.AbstractContraller;
import kr.co.sdsway2.service.AvatarService;
import kr.co.sdsway2.service.PollInfBeanService;
import kr.co.sdsway2.service.PollQstService;
import kr.co.sdsway2.service.PtInfBeanService;
import kr.co.sdsway2.service.PtService;
import kr.co.sdsway2.vo.AvatarVO;
import kr.co.sdsway2.vo.PracticeDataVO;
import kr.co.sdsway2.vo.PtInfVO;

import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class DashBoardController extends AbstractContraller {

	@Resource(name="avatarService")
	private AvatarService avatarService;

	@Resource(name="pollQstService")
	private PollQstService pollQstService;

	@Resource(name="ptInfBeanService")
	PtInfBeanService ptInfBeanService;

	@Resource(name="pollInfBeanService")
	PollInfBeanService pollInfBeanService;
	
	@Resource(name="practiceInfBeanList")
	List<PracticeDataVO> practiceDataList;

	@Resource(name="ptService")
	private PtService ptService;

	@RequestMapping("/dashBoard")
	public ModelAndView handleRequest(HttpServletRequest req, HttpServletResponse res) throws Exception {
		String authCd = req.getParameter("authCd");
		String tempKeyword = req.getParameter("tempKeyword");
		if( !"2212".equals(authCd) || !"right".equals(tempKeyword) ) {
			List<PtInfVO> ptInfVOList = ptService.getAllPtInf(null);
			ModelAndView mav = new ModelAndView("index.jsp");//view
			mav.addObject("ptInfVOList",ptInfVOList);
			return mav;
		}

		ModelAndView mav = new ModelAndView("dashBoard.jsp");

		//[TEMP] 디버그용
//		List<AvatarVO> avatarVOList = avatarService.getList();
//		if( avatarVOList != null ) {
//			debug("[TEMP] ### avatarVOList - " + String.valueOf(avatarVOList.size()));
//			for(int i=0; i<avatarVOList.size(); i++) {
//				debug("[TEMP] id(x, y) - score : " + avatarVOList.get(i).getAvatarId() + "(" + avatarVOList.get(i).getPosX() + ", " + avatarVOList.get(i).getPosY() + ") - " + avatarVOList.get(i).getAvatarScore());
//			}
//		}
		PtInfVO vo = ptInfBeanService.getPtInfBean(1);
		if(vo == null) vo = ptInfBeanService.insertPtInfBean(1, "20", "YOU ON A DIET");
		
		mav.addObject("ptInfVO",  ptInfBeanService.getPtInfBean(1));	//아바타 목록 조회
		mav.addObject("avatarVOList", avatarService.getList());	//아바타 목록 조회
		return mav;
	}

	/* ##### AJAX S ################################################## */
	@RequestMapping("/refreshAvatar")
	public ModelAndView ajaxRefreshAvatar(HttpServletRequest req, HttpServletResponse res) throws Exception {
		ModelAndView mav = new ModelAndView();

		mav.addObject("avatarVOList", avatarService.getList());	//아바타 목록 조회
		mav.addObject("ptInfVO", ptInfBeanService.getPtInfBean(1));	//현재 상태 리턴
		return mav;
	}

	@RequestMapping("/deleteAvatar")
	public void ajaxDeleteAvatar(Model model, HttpServletRequest req) throws Exception {
		String avatarId = req.getParameter("avatarId");
		if( avatarId == null ) return ;
		avatarService.remove(avatarId);	//아바타 삭제(아바타ID)
		model.addAttribute("avatarVOList", avatarService.getList());	//아바타 목록 조회
		model.addAttribute("ptInfVO", ptInfBeanService.getPtInfBean(1));	//현재 상태 리턴
	}
	
	
	/** 설문 시작 */
	@RequestMapping("/startPoll")
	public void ajaxStartPoll(Model model, HttpServletRequest req) throws Exception {
		String qstTypeCd = req.getParameter("qstTypeCd");
		String qstVal = req.getParameter("qstVal");
		if ("SUB".equals(qstTypeCd) && !SdsWay2Util.isNull(qstVal)) {
			qstVal = qstVal.replaceAll("#amp#", "&");
		}

//		debug("[TEMP] qType : " + qstTypeCd);
//		debug("[TEMP] qstVal : " + qstVal);
		if( qstTypeCd==null || qstTypeCd.length()==0 ) {
			return ;
		}

		String objOpt1 = req.getParameter("objOpt1");
		String objOpt2 = req.getParameter("objOpt2");
		String objOpt3 = req.getParameter("objOpt3");
		String objOpt4 = req.getParameter("objOpt4");
		String optPoint1 = req.getParameter("optPoint1");
		String optPoint2 = req.getParameter("optPoint2");
		String optPoint3 = req.getParameter("optPoint3");
		String optPoint4 = req.getParameter("optPoint4");

		HashMap<String, String> inputMap = new HashMap<String, String>();
		inputMap.put("qstTypeCd", qstTypeCd);
		inputMap.put("qstVal", qstVal);
		if( "OBJ".equals(qstTypeCd) ) {
			inputMap.put("objOpt1", objOpt1);
			inputMap.put("objOpt2", objOpt2);
			inputMap.put("objOpt3", objOpt3);
			inputMap.put("objOpt4", objOpt4);
			inputMap.put("optPoint1", optPoint1);
			inputMap.put("optPoint2", optPoint2);
			inputMap.put("optPoint3", optPoint3);
			inputMap.put("optPoint4", optPoint4);
		}
		else if( "OX".equals(qstTypeCd) ) {
			inputMap.put("objOpt1", objOpt1);
			inputMap.put("objOpt2", objOpt2);
			inputMap.put("optPoint1", optPoint1);
			inputMap.put("optPoint2", optPoint2);
		}

		HashMap<String, Integer> outputMap = pollQstService.insertPollQst(inputMap);
		if( outputMap != null ) {
			model.addAttribute("ptId", outputMap.get("ptId"));
			model.addAttribute("pollId", outputMap.get("pollId"));

			//[TEMP] 디버그용
//			List<AvatarVO> voList = avatarService.getList();
//			debug("=====================================");
//			for(int i=0; i<voList.size(); i++) {
//				debug(i + " >>>>> " + voList.get(i));
//			}
//			debug("=====================================");
	
			debug(">>>>>	obj poll insert complete!");
			debug(">>>>>	current PtInf : "+ ptInfBeanService.getList());
			debug(">>>>>	current PollInf : "+ pollInfBeanService.getList());
			
			//현재 상태 반환
			PtInfVO ptInfVO = ptInfBeanService.getPtInfBean(outputMap.get("ptId"));
			model.addAttribute("ptInfVO", ptInfVO);
		}
	}

	@RequestMapping("/terminatePoll")
	public void ajaxTerminatePoll(Model model, HttpServletRequest req) throws Exception {
		String ptId = req.getParameter("ptId");
		String pollId = req.getParameter("pollId");
		if( ptId==null || pollId==null ) return ;
		pollQstService.deletePollQst(ptId,pollId);
		
		//현재 상태 반환
		PtInfVO ptInfVO = ptInfBeanService.getPtInfBean(Integer.parseInt(ptId));
		model.addAttribute("ptInfVO", ptInfVO);
		
	}
	
	@RequestMapping("/alterPtStatCd")
	public void ajaxAlterPtStatCd(Model model, HttpServletRequest req) throws Exception {
		String ptId = req.getParameter("ptId");
		String ptStatCd = req.getParameter("ptStatCd");
		String successYn = "Y";
		try{
			ptInfBeanService.update(Integer.parseInt(ptId), ptStatCd, null);
		}catch(NumberFormatException e){
			error("입력된 pt ID 숫자 형식이 아닙니다.");
			successYn = "N";
		}
		
		//현재 상태 반환
		PtInfVO ptInfVO = ptInfBeanService.getPtInfBean(Integer.parseInt(ptId));
		model.addAttribute("ptInfVO", ptInfVO);
		model.addAttribute("successYn",successYn);
		
	}
	
	@RequestMapping("/sendMessage")
	public void ajaxSendMessage(Model model, HttpServletRequest req) throws JsonProcessingException, IOException {
		String practiceMessage = (String) req.getParameter("practiceMessage");
		debug("test::");
		PtInfVO ptInfVO = ptInfBeanService.getPtInfBean(1);
		if(ptInfVO==null) ptInfVO = ptInfBeanService.insertPtInfBean(1, "50", "YOU ON A DIET");
		
		ptInfVO.setMessage(practiceMessage);
		ptInfVO.setPtStatCd("50");
		debug("ptInfBeanService.getList():"+ptInfBeanService.getList());
		model.addAttribute("ptInfVO", ptInfBeanService.getPtInfBean(1));	//현재 상태 리턴
	}
	
	@RequestMapping("/terminateMessage")
	public void ajaxTerminateMessage(Model model, HttpServletRequest req) throws JsonProcessingException, IOException {
		PtInfVO ptInfVO = ptInfBeanService.getPtInfBean(1);
		if(ptInfVO==null) ptInfVO = ptInfBeanService.insertPtInfBean(1, "50", "YOU ON A DIET");
		ptInfVO.setMessage(null);
		model.addAttribute("ptInfVO", ptInfBeanService.getPtInfBean(1));	//현재 상태 리턴
	}
	
	@RequestMapping("/startSequencialPractice")
	public void ajaxStartSequencialPractice(Model model, HttpServletRequest req) throws JsonProcessingException, IOException {
		
		String practiceData = req.getParameter("practiceData");
		
		practiceDataList.clear();
		
		ObjectMapper om = new ObjectMapper();
		JsonNode jn = om.readTree(practiceData);
		if (jn.isArray()) {
			Iterator<JsonNode> i = jn.iterator();
			while (i.hasNext()) {
				JsonNode objAsw = i.next();
				
				PracticeDataVO inVO = new PracticeDataVO();
				String message = objAsw.get("message").getTextValue();
				if (SdsWay2Util.isNull(message)) {
					continue;
				}
				
				inVO.setMessage(message);
				inVO.setSustainmentTime(Integer.parseInt(objAsw.get("sustainmentTime").getTextValue()));
				practiceDataList.add(inVO);
			}
		}
		
		PtInfVO ptInfVO = ptInfBeanService.getPtInfBean(1);
		if(ptInfVO==null){
			ptInfBeanService.insertPtInfBean(1, "50", "YOU ON A DIET");
			ptInfVO = ptInfBeanService.getPtInfBean(1);
		}
		ptInfVO.setPtStatCd("50");
		//debug(practiceDataList);
		model.addAttribute("ptInfVO", ptInfBeanService.getPtInfBean(1));	//현재 상태 리턴
	}

	@RequestMapping("setAvatarScore")
	public void ajaxSetAvatarScore(Model model, HttpServletRequest req) throws JsonProcessingException, IOException {
		String avatarId = req.getParameter("avatarId");
		int avatarScore = Integer.parseInt(req.getParameter("avatarScore"));
//		debug("[TEMP] avatarId(avatarScore) : " + avatarId + "(" + avatarScore + ")");
		AvatarVO avatarVO = avatarService.getAvatar(avatarId);
		avatarVO.setAvatarScore(avatarScore);
		avatarService.sortAvatarVOList();
		
		//[TEMP] 디버그용
//		List<AvatarVO> avatarVOList = avatarService.getList();
//		debug("=====================================");
//		for(int i=0; i<avatarVOList.size(); i++) {
//			debug(i + " >>>>> " + avatarVOList.get(i));
//		}
//		debug("=====================================");

		model.addAttribute("ptInfVO", ptInfBeanService.getPtInfBean(1));	//현재 상태 리턴
	}
	/* ##### AJAX E ################################################## */

}
